package com.xukai.springboot.util.wx;

import com.alibaba.fastjson.JSONObject;
import com.xukai.springboot.util.http.HttpUtil;

import java.io.IOException;

public class WxOauthUtil {


    /**
     * 获取access_token url 地址
     */
    String access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";

    /**
     * 刷新access_token URL 地址
     */
    String refresh_token_url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=%s";

    /**
     * 验证access_token是否有效
     */
    String check_access_url = "https://api.weixin.qq.com/sns/auth?access_token=%s&openid=%s";

    /**
     * 获取微信用户
     */
    String get_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s";

    /**
     * 应用唯一标识
     */
    private String appID;

    /**
     * 应用密钥
     */
    private String secret;


    /**
     * 实例
     */
    private static WxOauthUtil instance = null;

    /**
     * 构造函数
     *
     * @param AppID
     * @param Secret
     */
    public WxOauthUtil(String AppID, String Secret) {
        this.appID = AppID;
        this.secret = Secret;
    }

    /**
     * 获取实例
     *
     * @param AppID  应用唯一标识
     * @param Secret 应用密钥
     * @return
     */
    public static WxOauthUtil GetInstance(String AppID, String Secret) {
        if (instance == null) {
            synchronized (WxOauthUtil.class) {
                if (instance == null) {
                    instance = new WxOauthUtil(AppID, Secret);
                }
            }
        }
        return instance;
    }

    /**
     * 获取用户access_token
     *
     * @param Code
     * @return
     */
    public WxAccessTokenResult Access_Token(String Code) throws IOException {
        WxAccessTokenResult result = new WxAccessTokenResult();
        try {
            //格式化访问路径
            String url = String.format(access_token_url, this.appID, this.secret, Code);
            //请求网络访问
            String data = new HttpUtil().doGet(url);
            //解析返回数据
            JSONObject resultJson = JSONObject.parseObject(data);

            //判断是否存在错误编号
            if (resultJson.containsKey("errcode")) {
                //设置错误编号
                result.setErrcode(resultJson.getInteger("errcode"));
                //获取错误信息
                if (resultJson.containsKey("errmsg")) {
                    result.setErrmsg(resultJson.getString("errmsg"));
                }
            } else {
                //获取access_token
                if (resultJson.containsKey("access_token")) {
                    result.setAccess_token(resultJson.getString("access_token"));
                }
                //获取expires_in
                if (resultJson.containsKey("expires_in")) {
                    result.setExpires_in(resultJson.getInteger("expires_in"));
                }
                //获取refresh_token
                if (resultJson.containsKey("refresh_token")) {
                    result.setRefresh_token(resultJson.getString("refresh_token"));
                }
                //获取openid
                if (resultJson.containsKey("openid")) {
                    result.setOpenid(resultJson.getString("openid"));
                }
                //获取scope
                if (resultJson.containsKey("scope")) {
                    result.setOpenid(resultJson.getString("scope"));
                }
            }

        } catch (Exception ex) {
            throw ex;
        }
        return result;
    }

    /**
     * 刷新Token
     *
     * @param RefreshToken
     * @return
     */
    public RefreshTokenResult Refresh_Token(String RefreshToken) throws IOException {
        RefreshTokenResult result = new RefreshTokenResult();
        try {
            //格式化url
            String url = String.format(refresh_token_url, this.appID, RefreshToken);
            //解析返回数据
            String data = new HttpUtil().doGet(url);
            //解析返回数据
            JSONObject resultJson = JSONObject.parseObject(data);
            //判断是否存在错误编号
            if (resultJson.containsKey("errcode")) {
                //设置错误编号
                result.setErrcode(resultJson.getInteger("errcode"));
                //获取错误信息
                if (resultJson.containsKey("errmsg")) {
                    result.setErrmsg(resultJson.getString("errmsg"));
                }
            } else {
                //获取access_token
                if (resultJson.containsKey("access_token")) {
                    result.setAccess_token(resultJson.getString("access_token"));
                }
                //获取expires_in
                if (resultJson.containsKey("expires_in")) {
                    result.setExpires_in(resultJson.getInteger("expires_in"));
                }
                //获取refresh_token
                if (resultJson.containsKey("refresh_token")) {
                    result.setRefresh_token(resultJson.getString("refresh_token"));
                }
                //获取openid
                if (resultJson.containsKey("openid")) {
                    result.setOpenid(resultJson.getString("openid"));
                }
                //获取scope
                if (resultJson.containsKey("scope")) {
                    result.setOpenid(resultJson.getString("scope"));
                }
            }

        } catch (
                Exception e) {
            throw e;
        }
        return result;
    }

    /**
     * 检验access_token是否有效
     */
    public CheckAccessTokenResult Check_Access_Token(String AccessToken, String OpenID) throws IOException {

        CheckAccessTokenResult result = new CheckAccessTokenResult();
        try {
            String url = String.format(check_access_url, AccessToken, OpenID);
            //解析返回数据
            String data = new HttpUtil().doGet(url);
            //解析返回数据
            JSONObject resultJson = JSONObject.parseObject(data);
            //判断是否存在错误编号
            if (resultJson.containsKey("errcode")) {
                //设置错误编号
                result.setErrcode(resultJson.getInteger("errcode"));
                //获取错误信息
                if (resultJson.containsKey("errmsg")) {
                    result.setErrmsg(resultJson.getString("errmsg"));
                }
            }
        } catch (Exception ex) {
            throw ex;
        }
        return result;
    }

    /**
     * 获取微信用户信息
     *
     * @param AccessToken
     * @param OpenID
     * @return
     */
    public GetUserInfoResult GetUserInfor(String AccessToken, String OpenID) {
        GetUserInfoResult result = new GetUserInfoResult();
        try {

            String url = String.format(get_user_info_url, AccessToken, OpenID);
            //解析返回数据
            String data = new HttpUtil().doGet(url);
            //解析返回数据
            JSONObject resultJson = JSONObject.parseObject(data);
            //判断是否存在错误编号
            if (resultJson.containsKey("errcode")) {
                //设置错误编号
                result.setErrcode(resultJson.getInteger("errcode"));
                //获取错误信息
                if (resultJson.containsKey("errmsg")) {
                    result.setErrmsg(resultJson.getString("errmsg"));
                }
            } else {
                //获取openid
                if (resultJson.containsKey("openid")) {
                    result.setOpenid(resultJson.getString("openid"));
                }
                //获取nickname
                if (resultJson.containsKey("nickname")) {
                    result.setNickname(resultJson.getString("nickname"));
                }
                //获取sex
                if (resultJson.containsKey("sex")) {
                    result.setSex(resultJson.getInteger("sex"));
                }
                //获取province
                if (resultJson.containsKey("province")) {
                    result.setProvince(resultJson.getString("province"));
                }
                //获取city
                if (resultJson.containsKey("city")) {
                    result.setCity(resultJson.getString("city"));
                }
                //获取country
                if (resultJson.containsKey("country")) {
                    result.setCountry(resultJson.getString("country"));
                }
                //获取headimgurl
                if (resultJson.containsKey("headimgurl")) {
                    result.setCountry(resultJson.getString("headimgurl"));
                }
                //获取unionid
                if (resultJson.containsKey("unionid")) {
                    result.setCountry(resultJson.getString("unionid"));
                }
            }
        } catch (Exception ex) {
        }
        return result;
    }
}
